package com.ruoyi.generator.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.GenConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.generator.domain.GenTable;
import com.ruoyi.generator.domain.GenTableColumn;
import com.ruoyi.generator.domain.Templates;
import org.apache.velocity.VelocityContext;

import java.util.*;

/**
 * 模板处理工具类
 *
 * @author ruoyi
 */
public class VelocityUtils {
    /**
     * 项目空间路径
     */
    private static final String PROJECT_PATH = "main/java";

    /**
     * mybatis空间路径
     */
    private static final String MYBATIS_PATH = "main/resources/mapper";

    /**
     * 默认上级菜单，顶级目录
     */
    private static final String DEFAULT_PARENT_MENU_ID = "0";

    /**
     * 设置模板变量信息
     *
     * @return 模板列表
     */
    public static VelocityContext prepareContext(GenTable genTable) {
        String moduleName = genTable.getModuleName();
        String businessName = genTable.getBusinessName();
        String packageName = genTable.getPackageName();
        String functionName = genTable.getFunctionName();
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("tableName", genTable.getTableName());
        velocityContext.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "AX");
        velocityContext.put("ClassName", genTable.getClassName());
        velocityContext.put("className", StringUtils.uncapitalize(genTable.getClassName()));
        velocityContext.put("moduleName", genTable.getModuleName());
        velocityContext.put("ModuleName", StringUtils.capitalize(genTable.getModuleName()));
        velocityContext.put("BusinessName", StringUtils.capitalize(genTable.getBusinessName()));
        velocityContext.put("businessName", genTable.getBusinessName());
        velocityContext.put("basePackage", getPackagePrefix(packageName));
        velocityContext.put("packageName", packageName);
        velocityContext.put("author", genTable.getFunctionAuthor());
        // pkColumn为空，待解决
        velocityContext.put("pkColumn", genTable.getPkColumn());
        velocityContext.put("importList", getImportList(genTable));
        velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName));
        velocityContext.put("columns", genTable.getColumns());
        velocityContext.put("table", genTable);
        velocityContext.put("dicts", getDicts(genTable));
        setMenuVelocityContext(velocityContext, genTable);
        return velocityContext;
    }

    public static void setMenuVelocityContext(VelocityContext context, GenTable genTable) {
        if (genTable.getOptions() != null) {
            String options = genTable.getOptions().toString();
            JSONObject paramsObj = JSON.parseObject(options);
            String parentMenuId = getParentMenuId(paramsObj);
            context.put("parentMenuId", parentMenuId);
        }

    }

    public static String getVueTemplate(String style) {
        return "";
    }

    /**
     * 获取模板信息
     *
     * @param type
     *        mobile:仅移动端
     *        mobile-java:移动端+java
     *        pc-java:PC端+java
     *        java:仅后端
     *        pc:仅PC端
     *        api：仅前端API接口
     * @return 模板列表
     */
    public static List<String> getTemplateList(String type) {
        List<String> templates = new ArrayList<>();
        switch (type) {
            case "MOBILE_JAVA":
                templates.addAll(Arrays.asList(Templates.mobileTemplates));
                templates.addAll(Arrays.asList(Templates.apiTemplates));
                templates.addAll(Arrays.asList(Templates.javaTemplates));
                templates.addAll(Arrays.asList(Templates.sqlTemplate));
                break;
            case "PC_JAVA":
                /*如果是PC端，则渲染这里*/
                templates.addAll(Arrays.asList(Templates.pcTemplates));
                templates.addAll(Arrays.asList(Templates.apiTemplates));
                templates.addAll(Arrays.asList(Templates.javaTemplates));
                templates.addAll(Arrays.asList(Templates.sqlTemplate));
                break;
            case "JAVA":
                templates.addAll(Arrays.asList(Templates.javaTemplates));
                break;

            case "MOBILE":
                templates.addAll(Arrays.asList(Templates.mobileTemplates));
                break;

            case "SQL":
                templates.addAll(Arrays.asList(Templates.sqlTemplate));
                break;

            case "PC":
                templates.addAll(Arrays.asList(Templates.pcTemplates));
                templates.addAll(Arrays.asList(Templates.apiTemplates));
                break;

            case "API":
                templates.addAll(Arrays.asList(Templates.apiTemplates));
                break;
        }
        return templates;

    }


    /**
     * @param template 模版字符串
     * @param genTable 表相关的配置
     * @return 文件名
     */
    public static String getFileName(String template, GenTable genTable) {
        // 文件名称
        String fileName = "";
        // 包路径
        String packageName = genTable.getPackageName();
        // 模块名
        String moduleName = genTable.getModuleName();
        // 大写类名
        String className = genTable.getClassName();
        // 业务名称
        String businessName = genTable.getBusinessName();

        String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/");
        String mybatisPath = MYBATIS_PATH + "/" + moduleName;
        String vuePath = "vue";

        // Define a map to store template mappings
        Map<String, String> templateToFileMap = new HashMap<>();

        templateToFileMap.put("domain.java.vm", "{}/domain/{}.java");
        templateToFileMap.put("mapper.java.vm", "{}/mapper/{}Mapper.java");
        templateToFileMap.put("service.java.vm", "{}/service/I{}Service.java");
        templateToFileMap.put("serviceImpl.java.vm", "{}/service/impl/{}ServiceImpl.java");
        templateToFileMap.put("controller.java.vm", "{}/controller/{}Controller.java");
        templateToFileMap.put("mapper.xml.vm", "{}/{}Mapper.xml");
        templateToFileMap.put("sql.vm", "{}Menu.sql");


        Map<String, String> vueMap = new HashMap<>();

        /* 渲染PC端的文件名 */
        // vueMap.put(vm的路径, 生成的文件名);
        vueMap.put("curd.ts.vm", "{}/views/modules/{}/{}/data/curd.ts");
        vueMap.put("column.ts.vm", "{}/views/modules/{}/{}/data/column.ts");
        vueMap.put("card.ts.vm", "{}/views/modules/{}/{}/data/card.ts");
        vueMap.put("table.ts.vm", "{}/views/modules/{}/{}/data/table.ts");
        vueMap.put("form.ts.vm", "{}/views/modules/{}/{}/data/form.ts");
        vueMap.put("form.message.ts.vm", "{}/views/modules/{}/{}/data/form.message.ts");
        vueMap.put("form.actions.ts.vm", "{}/views/modules/{}/{}/data/form.actions.ts");
        vueMap.put("options.ts.vm", "{}/views/modules/{}/{}/data/options.ts");
        //页面
        vueMap.put("pages/index.vue.vm", "{}/views/modules/{}/{}/index.vue");
        vueMap.put("pages/AXForm.vue.vm", "{}/views/modules/{}/{}/form/AXForm.vue");
        vueMap.put("pages/AXFooter.vue.vm", "{}/views/modules/{}/{}/pages/footer/AXFooter.vue");
        vueMap.put("pages/AXHead.vue.vm", "{}/views/modules/{}/{}/pages/head/AXHead.vue");
        vueMap.put("pages/AXCard.vue.vm", "{}/views/modules/{}/{}/pages/card/AXCard.vue");
        vueMap.put("pages/AXTable.vue.vm", "{}/views/modules/{}/{}/pages/table/AXTable.vue");
        vueMap.put("readme.md.vm", "{}/views/modules/{}/{}/readme.md");

        /*
         * 渲染移动端
        */
        vueMap.put("mobile/index.vue.vm", "{}/views/modules/{}/{}/index.vue");
        vueMap.put("view/Data.vue.vm", "{}/views/modules/{}/{}/view/Data.vue");
        vueMap.put("view/Head.vue.vm", "{}/views/modules/{}/{}/view/Head.vue");
        vueMap.put("view/View.vue.vm", "{}/views/modules/{}/{}/view/View.vue");
        vueMap.put("form/Form.vue.vm", "{}/views/modules/{}/{}/form/Form.vue");
        vueMap.put("components/Sort.vue.vm", "{}/views/modules/{}/{}/view/components/Sort.vue");
        vueMap.put("components/Setting.vue.vm", "{}/views/modules/{}/{}/view/components/Setting.vue");
        vueMap.put("components/Search.vue.vm", "{}/views/modules/{}/{}/view/components/Search.vue");

        /* 渲染vue文件 */
        for (Map.Entry<String, String> entry : vueMap.entrySet()) {
            if (template.contains(entry.getKey())) {
                fileName = StringUtils.format(entry.getValue(), vuePath, moduleName, businessName);
                break;
            }
        }

        for (Map.Entry<String, String> entry : templateToFileMap.entrySet()) {
            if (template.contains(entry.getKey())) {
                if ("sql.vm".equals(entry.getKey())) {
                    fileName = businessName + "Menu.sql";
                } else {
                    fileName = StringUtils.format(entry.getValue(),
                            entry.getKey().contains("mapper.xml.vm") ? mybatisPath : javaPath,
                            className);
                }
                break;
            }
        }

        /*
         *  API 生成
         * 类型生成
         * */
        if (template.contains("api.ts.vm")) {
            fileName = StringUtils.format("{}/api/modules/{}/{}/{}.ts", vuePath, moduleName, businessName, businessName);
        } else if (template.contains("types.ts.vm")) {
            fileName = StringUtils.format("{}/api/modules/{}/{}/types.ts", vuePath, moduleName, businessName);
        }

        return fileName;
    }

    /**
     * 获取包前缀
     *
     * @param packageName 包名称
     * @return 包前缀名称
     */
    public static String getPackagePrefix(String packageName) {
        int lastIndex = packageName.lastIndexOf(".");
        return StringUtils.substring(packageName, 0, lastIndex);
    }

    /**
     * 根据列类型获取导入包
     *
     * @param genTable 业务表对象
     * @return 返回需要导入的包列表
     */
    public static HashSet<String> getImportList(GenTable genTable) {
        List<GenTableColumn> columns = genTable.getColumns();
        HashSet<String> importList = new HashSet<String>();

        for (GenTableColumn column : columns) {
            if (!column.isSuperColumn() && GenConstants.TYPE_DATE.equals(column.getJavaType())) {
                importList.add("java.util.Date");
                importList.add("com.fasterxml.jackson.annotation.JsonFormat");
            } else if (!column.isSuperColumn() && GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType())) {
                importList.add("java.math.BigDecimal");
            }
        }
        return importList;
    }

    /**
     * 根据列类型获取字典组
     *
     * @param genTable 业务表对象
     * @return 返回字典组
     */
    public static String getDicts(GenTable genTable) {
        List<GenTableColumn> columns = genTable.getColumns();
        Set<String> dicts = new HashSet<String>();
        addDicts(dicts, columns);
        return StringUtils.join(dicts, ", ");
    }

    /**
     * 添加字典列表
     *
     * @param dicts   字典列表
     * @param columns 列集合
     */
    public static void addDicts(Set<String> dicts, List<GenTableColumn> columns) {
        for (GenTableColumn column : columns) {
            if (!column.isSuperColumn() && StringUtils.isNotEmpty(column.getDictType()) && StringUtils.equalsAny(
                    column.getHtmlType(),
                    new String[]{GenConstants.HTML_SELECT, GenConstants.HTML_RADIO, GenConstants.HTML_CHECKBOX})) {
                dicts.add("'" + column.getDictType() + "'");
            }
        }
    }

    /**
     * 获取权限前缀
     *
     * @param moduleName   模块名称
     * @param businessName 业务名称
     * @return 返回权限前缀
     */
    public static String getPermissionPrefix(String moduleName, String businessName) {
        return StringUtils.format("{}:{}", moduleName, businessName);
    }

    /**
     * 获取上级菜单ID字段
     *
     * @param paramsObj 生成其他选项
     * @return 上级菜单ID字段
     */
    public static String getParentMenuId(JSONObject paramsObj) {
        if (StringUtils.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_MENU_ID)
                && StringUtils.isNotEmpty(paramsObj.getString(GenConstants.PARENT_MENU_ID))) {
            return paramsObj.getString(GenConstants.PARENT_MENU_ID);
        }
        return DEFAULT_PARENT_MENU_ID;
    }

}
